package com.yakaten.service;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.CookieHandler;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.IOUtils;

import com.yakaten.exception.RakutenException;
import com.yakaten.login.CorrectedCookieManager;
import com.yakaten.login.RakutenLogin;
import com.yakaten.login.RakutenLoginRmsItem;
import com.yakaten.login.RakutenLoginRmsOrder;

public class RakutenItemService {

	private static final String ITEM_INFO_URL = "https://item.rms.rakuten.co.jp/rms/mall/rsf/item/vc?__event=RI03_001_002&shop_bid=";

	private static final String ITEM_UPDATE_URL="https://item.rms.rakuten.co.jp/rms/mall/rsf/item/vc";

	private static final String REGEX_INPUT = "<input(.+?)>";

	private static final Pattern PATTERN_INPUT = Pattern.compile(REGEX_INPUT);

	private static final String REGEX_SELECT = "<select(.+?)</select>";

	private static final Pattern PATTERN_SELECT = Pattern.compile(REGEX_SELECT);

	private static final String REGEX_OPTION = "<option(.+?)>";

	private static final Pattern PATTERN_OPTION = Pattern.compile(REGEX_OPTION);


	private static final String REGEX_TEXTAREA = "<textarea(.+?)</textarea>";

	private static final Pattern PATTERN_TEXTAREA = Pattern.compile(REGEX_TEXTAREA);

	private static final String REGEX_TEXTAREA_VALUE = "<textarea(.+?)>(.+?)</textarea>";

	private static final Pattern PATTERN_TEXTAREA_VALUE = Pattern.compile(REGEX_TEXTAREA_VALUE);


	private static final String REGEX_INPUT_TYPE = "type=[\"|']{1}(.+?)[\"|']{1}";

	private static final Pattern PATTERN_INPUT_TYPE = Pattern
			.compile(REGEX_INPUT_TYPE);

	private static final String REGEX_INPUT_NAME = "name=[\"|']{1}(.+?)[\"|']{1}";

	private static final Pattern PATTERN_INPUT_NAME = Pattern
			.compile(REGEX_INPUT_NAME);

	private static final String REGEX_INPUT_VALUE = "value=[\"|']{1}(.*?)[\"|']{1}";

	private static final Pattern PATTERN_INPUT_VALUE = Pattern
			.compile(REGEX_INPUT_VALUE);

	private static final String REGEX_INPUT_CHECKED = "checked=[\"|']{1}(.+?)[\"|']{1}";

	private static final Pattern PATTERN_INPUT_CHECKED = Pattern
			.compile(REGEX_INPUT_CHECKED);

	private static final String REGEX_INPUT_SELECTED = "selected";

	private static final Pattern PATTERN_INPUT_SELECTED = Pattern
			.compile(REGEX_INPUT_SELECTED);

	public Map<String, String> getItemInfo(String shopId, String mngNumber) throws RakutenException {

		String url = ITEM_INFO_URL + shopId + "&mng_number=" + mngNumber;
		URL targetUrl;
		BufferedReader bufferedReader = null;

		Map<String, String> resultMap = new HashMap<String, String>();
		try {
			targetUrl = new URL(url);
			HttpURLConnection resumeConnection = (HttpURLConnection) targetUrl
					.openConnection();
			resumeConnection.setRequestProperty("Cookie","shop="+new RakutenLoginRmsItem().getCookieShop(shopId));

			resumeConnection.connect();
			InputStream urlStream = resumeConnection.getInputStream();
			bufferedReader = new BufferedReader(new InputStreamReader(
					urlStream, "euc-jp"));
			String ss = null;
			StringBuffer total = new StringBuffer();
			while ((ss = bufferedReader.readLine()) != null) {
				total.append(ss);
			}

			Matcher matcherInput = PATTERN_INPUT.matcher(total);

			while (matcherInput.find()) {
				String input = matcherInput.group(1);
				// type
				String type = "";
				Matcher matcherInputType = PATTERN_INPUT_TYPE.matcher(input);
				if (matcherInputType.find()) {
					type = matcherInputType.group(1);
				}

				if ("button".equals(type.toLowerCase())) {
					continue;
				}

				if ("radio".equals(type.toLowerCase())) {
					Matcher matcherInputChecked = PATTERN_INPUT_CHECKED
							.matcher(input);
					if (!matcherInputChecked.find()) {
						continue;
					}
				}
				String name = "";
				Matcher matcherInputName = PATTERN_INPUT_NAME.matcher(input);
				if (matcherInputName.find()) {
					name = matcherInputName.group(1);
				}

				String value = "";
				Matcher matcherInputValue = PATTERN_INPUT_VALUE.matcher(input);
				if (matcherInputValue.find()) {
					value = matcherInputValue.group(1);
				}

				if (name.length() > 0) {
					resultMap.put(name, value);
				}
				// System.out.println("type:" + type + ",name:" + name +
				// ",value:"
				// + value);
			}

			Matcher matcherSelect = PATTERN_SELECT.matcher(total);

			while (matcherSelect.find()) {
				String select = matcherSelect.group(1);
				String name = "";
				Matcher matcherInputName = PATTERN_INPUT_NAME.matcher(select);
				if (matcherInputName.find()) {
					name = matcherInputName.group(1);
				}

				String value = "";
				Matcher matcherOption = PATTERN_OPTION.matcher(select);
				boolean selected = false;
				List<String> workList = new ArrayList<String>();
				while (matcherOption.find()) {
					String option = matcherOption.group(1);
					String workValue = "";
					Matcher matcherInputValue = PATTERN_INPUT_VALUE
							.matcher(option);
					if (matcherInputValue.find()) {
						workValue = matcherInputValue.group(1);
					}
					workList.add(workValue);
					Matcher matcherInputSelected = PATTERN_INPUT_SELECTED
							.matcher(option);
					if (matcherInputSelected.find()) {
						selected = true;
						break;
					}

				}

				if(selected){
					value = workList.get(workList.size()-1);
				}else{
					value = workList.get(0);
				}

				if (name.length() > 0) {
					resultMap.put(name, value);
				}
			}

			Matcher matcherTextarea = PATTERN_TEXTAREA.matcher(total);

			while (matcherTextarea.find()) {
				String textarea = matcherTextarea.group(0);
				String name = "";
				Matcher matcherInputName = PATTERN_INPUT_NAME.matcher(textarea);
				if (matcherInputName.find()) {
					name = matcherInputName.group(1);
				}

				Matcher matcherValue = PATTERN_TEXTAREA_VALUE.matcher(textarea);
				String value ="";
				if (matcherValue.find()) {
					value = matcherValue.group(2);
				}

				if (name.length() > 0) {
					resultMap.put(name, value);
				}
			}

			IOUtils
					.write(total, new FileOutputStream("c:/item.html"),
							"euc-jp");

		} catch (MalformedURLException e) {
			throw new RakutenException(e);
		} catch (IOException e) {
			throw new RakutenException(e);
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return resultMap;
	}

	public boolean updateItemInfo(String shopId,Map<String,String> valueMap) throws RakutenException{
		OutputStreamWriter out = null;
		HttpURLConnection connection = null;
		BufferedReader bufferedReader = null;

		try {
			URL updateUrl = new URL(ITEM_UPDATE_URL);
			connection = (HttpURLConnection) updateUrl.openConnection();
			connection.setRequestProperty("Cookie","shop="+new RakutenLoginRmsItem().getCookieShop(shopId));
			connection.setDoOutput(true);

			out = new OutputStreamWriter(connection.getOutputStream(), "euc-jp");

			StringBuffer para = new StringBuffer();

			Iterator<String> keyIt = valueMap.keySet().iterator();
			while(keyIt.hasNext()){
				String key = keyIt.next();
				String value = valueMap.get(key);
				para.append(key+"="+value+"&");
			}

			System.out.println(para);
			out.write(para.toString());
			out.flush();

			InputStream urlStream = connection.getInputStream();
			bufferedReader = new BufferedReader(new InputStreamReader(
					urlStream, "euc-jp"));
			String ss = null;
			StringBuffer total = new StringBuffer();
			while ((ss = bufferedReader.readLine()) != null) {
				total.append(ss);
			}

			IOUtils
			.write(total, new FileOutputStream("c:/updateresult.html"),
					"euc-jp");

		} catch (MalformedURLException e) {
			throw new RakutenException(e);
		} catch (IOException e) {
			throw new RakutenException(e);
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (connection != null) {
				connection.disconnect();
			}
		}


		return true;
	}
	public static void main(String args[]) {
		new RakutenLoginRmsItem().doLogin("");
		RakutenItemService service = new RakutenItemService();
		Map<String, String> valueMap;
		try {
			valueMap = service.getItemInfo("", "");
		} catch (RakutenException e) {
			e.printStackTrace();
		}
		

	}
}
